package com.myjianzhu.zzt88.exercise.java.utils;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class ClassForMap {
    public static void main(String[] args) {
        linkedHashMapShow();
        treeMapShow();
        hashTableShow();
    }

    public static void hashTableShow(){
        //HashTable是线程安全的一个Map，内部没有排序
        Hashtable<Integer,String> table = new Hashtable<>();
        table.put(1, "one");
        table.put(2, "two");
        table.put(4, "three");
        table.put(3, "four");
        table.put(5, "five");
        table.put(7, "six");
        table.put(6, "seven");
        System.out.println("----HashTable show Now----");
        printMap(table);

        Hashtable<String,String> strTable = new Hashtable<>();
        strTable.put("a","1");
        strTable.put("b","2");
        strTable.put("c","3");
        strTable.put("d","4");
        strTable.put("e","5");
        strTable.put("f","6");
        System.out.println("----HashTable String key show Now----");

        printMap(strTable);


    }

    public static void linkedHashMapShow() {
        //LinkedHashMap保存了记录的插入顺序
        //每次调用get方法，If the enclosing Map is access-ordered, it moves the entry
        //* to the end of the list;
        boolean accessOrder = true;
        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>(0, 0.75f, accessOrder);
        linkedHashMap.put(1, "one");
        linkedHashMap.put(2, "two");
        linkedHashMap.put(3, "three");
        linkedHashMap.put(4, "four");
        System.out.println("----LinkedHashMap show Now----");

        printMap(linkedHashMap);

        linkedHashMap.get(2);
        printMap(linkedHashMap);

    }

    public static void treeMapShow(){
        //TreeMap实现SortMap接口，能够把它保存的记录根据键排序,默认是按键值的升序排序，也可以指定排序的比较器，当用Iterator 遍历TreeMap时，得到的记录是排过序的。
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(1, "one");
        map.put(3, "two");
        map.put(2, "three");
        map.put(0, "four");
        System.out.println("----treeMap show Now----");
        printMap(map);
    }

    private static void printMap(Map map) {
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            System.out.println("Key: " + e.getKey() + "--Value: "
                    + e.getValue() + " hash of key " + e.getKey().hashCode());
        }
    }
}
